import axios from 'axios'
import router from '@/router'
import qs from 'qs'
import { getToken, removeToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: 'http://localhost:80/maple-farm-products-traceability/',
  timeout: 3000,
  transformRequest: [data => qs.stringify(data)]
})

service.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded;charset=UTF-8'

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = getToken()
    return config
  },
  error => {
    // Message({
    //   message: error,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== SUCCESS) {
      return errorHandler(res)
    } else {
      return res
    }
  },
  error => {
    // Message({
    //   message: error,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

// 操作成功
const SUCCESS = 200
// 操作失败
const FAILED = 500
// 请求未认证
const UNAUTHORIZED = 401
// 没有相关权限
const FORBIDDEN = 403
// 参数检验失败
const NOTACCEPTABLE = 406

const errorHandler = result => {
  let message = null
  switch (result.code) {
    case FAILED:
      message = result.message
        ? result.message
        : '请求成功但未通过请求目标资源未达到预期目的'
      break
    case UNAUTHORIZED:
      message = result.message ? result.message : '账户过期表示在线状态过期'
      toLogin()
      break
    case FORBIDDEN:
      message = result.message ? result.message : '请求参数错误'
      break
    case NOTACCEPTABLE:
      message = result.message ? result.message : '参数检验失败'
      break
    case SUCCESS:
      break
    default:
      message = '未知错误'
      break
  }
  console.log(message)
  return result
}

const toLogin = () => {
  removeToken()
  router.replace({
    path: '/login',
    query: {
      redirect: router.currentRoute.fullPath
    }
  })
}

export default service
